package com.yuesystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuesystem.common.BaseContext;
import com.yuesystem.common.CustomException;
import com.yuesystem.dto.responsebody.ApplyResponseBody;
import com.yuesystem.entity.Apply;
import com.yuesystem.entity.User;
import com.yuesystem.mapper.ApplyMapper;
import com.yuesystem.service.ApplyService;
import com.yuesystem.service.UserService;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 申请接口实现类.
 */
@Service
@Slf4j
public class ApplyServiceImpl extends ServiceImpl<ApplyMapper, Apply> implements ApplyService {

  @Autowired
  private UserService userService;

  /**
   * 根据用户ID查询是否该用户已申请.
   *
   * @param userId 用户id
   * @return 申请类
   */
  @Override
  public Apply getByUserId(Long userId) {
    LambdaQueryWrapper<Apply> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(Apply::getUserId, userId)
        .eq(Apply::getStatus, 0);
    Apply one = this.getOne(queryWrapper);
    return one;
  }

  /**
   * 用户申请成为编辑或客服.
   *
   * @param userId 用户id
   */
  @Override
  public void add(Long userId) {
    if (this.getByUserId(userId) != null) {
      throw new CustomException("您已申请，请耐心等待审核哦~");
    }
    Apply apply = new Apply();
    apply.setUserId(userId);
    apply.setApplyTime(LocalDateTime.now());
    apply.setStatus(0);
    apply.setApplyToWho(1);
    this.save(apply);
  }

  /**
   * 分页查询未处理的申请.
   *
   * @param page     起始页
   * @param pageSize 页数
   * @return 申请响应类的分页形式
   */
  @Override
  public Page<ApplyResponseBody> getPage(int page, int pageSize) {
    Page<Apply> applyPage = new Page<>(page, pageSize);

    LambdaQueryWrapper<Apply> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(Apply::getStatus, 0); //查询未处理的申请
    queryWrapper.orderByDesc(Apply::getApplyTime);  //时间倒叙

    // 根据条件分页查询
    this.page(applyPage, queryWrapper);
    Page<ApplyResponseBody> dtoPage = new Page<>(page, pageSize);
    // 把applyPage的内容拷贝到dtoPage中去，除了records不拷贝
    BeanUtils.copyProperties(applyPage, dtoPage, "records");

    List<Apply> records = applyPage.getRecords();

    List<ApplyResponseBody> dtoList = records.stream().map((item) -> {
      ApplyResponseBody applyResponseBody = new ApplyResponseBody();

      BeanUtils.copyProperties(item, applyResponseBody);
      Long userId = item.getUserId();  //获得用户ID
      User one = userService.getById(userId);
      String userName = one.getUserName();
      String phone = one.getPhone();

      if (one != null) {
        applyResponseBody.setUserName(userName);
        applyResponseBody.setUserPhone(phone);
//        applyResponseBody.setApplyToWho(item.getApplyToWho());
      }
      return applyResponseBody;
    }).collect(Collectors.toList());

    dtoPage.setRecords(dtoList);

    return dtoPage;
  }

  /**
   * 管理员同意某个申请.
   *
   * @param id 申请编号
   */
  @Override
  public void agree(Long id) {
    Long adminId = BaseContext.getCurrentId();
    Apply one = this.getById(id);
    one.setStatus(1);  // 改变status状态为1，即为同意申请
    one.setAdminId(adminId);
    one.setHandleTime(LocalDateTime.now());

    this.updateById(one); // 将更新后的apply重新存入数据库

    Long userId = one.getUserId();
    User user = userService.getById(userId);
    user.setStatus(one.getApplyToWho());  // 将用户的身份改为申请身份，1编辑3客服

    userService.updateById(user);
  }

  /**
   * 管理员拒绝某个申请.
   *
   * @param id 申请编号
   */
  @Override
  public void disagree(Long id) {
    Long adminId = BaseContext.getCurrentId();
    Apply one = this.getById(id);
    one.setStatus(2);  // 改变status状态为2，即为拒绝申请
    one.setAdminId(adminId);
    one.setHandleTime(LocalDateTime.now());

    this.updateById(one);
  }

  /**
   * 是否可申请.
   *
   * @param currentId 用户id
   * @return 是否可申请
   */
  @Override
  public Boolean judge(Long currentId) {
    //  如果不是用户，不可申请
    if (userService.getById(currentId).getStatus() != 0) {
      return false;
    }

    // 如果是用户
    LambdaQueryWrapper<Apply> queryWrapper = new LambdaQueryWrapper<>();

    // 已经申请过编辑的且未被处理的用户不能再次申请
    queryWrapper.eq(Apply::getUserId, currentId)
        .eq(Apply::getStatus, 0);
    Apply one = this.getOne(queryWrapper); //one不为空说明已经申请过了
    if (one != null) {
      return false;
    }
    return true;
  }

  /**
   * 根据用户id删除该用户的未被处理的申请.
   *
   * @param userId 用户id
   */
  @Override
  public void deleteById(Long userId) {
    LambdaQueryWrapper<Apply> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(Apply::getUserId, userId)
        .eq(Apply::getStatus, 0);
    this.remove(queryWrapper);
  }
}
